import {
	TokenKey
} from "../../vars/StoreKeys.js"
import Auth from "../../api/Auth.js"
import {
	isEmpty
} from "../../utils/helpers.js"
export default {
	namespaced: true,
	state: {
		token: null,
		userInfo: {
			"id": 0,
			"username": null,
			"cnname": null,
			"photo": null,
			"vip": 0,
			"set_voice": 0
		}

	},
	getters: {
		isEmptyUserInfo(state) {
			return isEmpty(state.userInfo.cnname) || isEmpty(state.userInfo.photo)
		}
	},
	mutations: {
		setToken(state, data) {
			state.token = data
		},
		setUserInfo(state, data) {

			state.userInfo = data || {}
		}
	},
	actions: {
		async updateUserInfoByWx({
			state,
			commit,
			dispatch,
		}, force = false) {
			if (!state.token) {
				await dispatch("getToken")
			}
			try {
				const data = await Auth.updateUserInfoByWx()
				commit('setUserInfo', data.info)
			} catch (e) {

			}
			return state.userInfo;
		},
		async getUserInfo({
			state,
			commit,
			dispatch,
		}, force = false) {
			if (!state.token) {
				await dispatch("getToken")
			}
			if (force || isEmpty(state.userInfo)) {
				try {
					const data = await Auth.getUserInfo()
					commit('setUserInfo', data.info)
				} catch (e) {

				}
			}
			return state.userInfo;
		},
		async getToken({
			state,
			commit,
			dispatch,
		}) {
			// if (!state.token) {
			// 	const token = uni.getStorageSync(TokenKey)
			// 	state.token = token
			// }
			if (!state.token) {
				try {
					const loginRes = await Auth.login()
					if (loginRes && loginRes.token) {
						commit('setToken', loginRes.token)
						commit('setUserInfo', loginRes.info)
						uni.setStorageSync(TokenKey, loginRes.token)
					}
				} catch (e) {

				}
			}
			return state.token
		},
		async getUserInfo({
			state,
			commit,
		}) {
			try {
				const res = await Auth.getUserInfo()
				commit('setUserInfo', res)
				console.log('getUserInfo:::::', res)
			} catch (e) {

			}
			return state.userInfo
		}
	}
}
